/**
    \file Gb2312_to_unicode.c

    COPYRIGHT(C) 2011,ShenZhen smit CO.,LTD. \n
    All rights reserved. \n\n

    \brief implement the charset interface.

    \details charset interface includes:
        -
    \version 1.1
    \date 2011-05-10
    \author wangxr
    \note Created
    
*/

/* Includes --------------------------------------------------------------- */

#include <stdio.h>
#include <stddef.h>
#include <string.h>
#include "usm_typedef.h"

#include "usm_charset.h"
#include "gb2312_to_unicode.h"

/* Private Macros --------------------------------------------------------- */

/* Private Types ---------------------------------------------------------- */

#define  UNICODE_ID			0x11
#define  UNSUPPORTED_CHAR		0x25A1  /*'?'*/

/* Private Constants ------------------------------------------------------ */

/* Private Variables (static) --------------------------------------------- ----*/

/* Global Variables ------------------------------------------------------- */

/* Private Function prototypes -------------------------------------------- --*/

/* Functions -------------------------------------------------------------*/

__inline static JZ_UINT16 GetGb2UniIndex( JZ_UCHAR gb[] )//unsigned char
{
	JZ_UCHAR ucQuMa = 0;
	JZ_UCHAR ucWeiMa = 0;

	ucQuMa = gb[0] - 0xa1;
	ucWeiMa = gb[1] - 0xa1;
	
	if ((ucQuMa < 0x57) && (ucWeiMa < 0x5E))
		return gb2312_unicode_list[ucQuMa][ucWeiMa];
	else
		return UNSUPPORTED_CHAR;

}


/**
    \fn JZ_Error_t USM_CS_GB2Unicode(JZ_WCHAR *pwszDest, const JZ_CHAR *pszSrc, JZ_INT32 nLength)

    \brief Converts a GB2312 string into a Unicode string.

    \param[out] pwszDest The destination wide-character string.
    \param[in] pszSrc The source string which charset format is GB2312.
    \param[in] nLength The length of the source string. The value of 0 represents the source string ends with a null character.

    \retval JZ_SUCCESS Successful.
    \retval JZ_FAILURE Failed.
    \retval JZ_ERROR_BAD_PARAMETER Bad parameter passed.

    \remark

    \see USM_CS_Unicode2GB
*/
JZ_Error_t USM_CS_GB2Unicode(JZ_WCHAR *pwszDest, const JZ_CHAR *pszSrc, JZ_INT32 nLength)
{
	JZ_UINT16 nUniCode;
	JZ_INT32 nOffsetSrcBuf = 0;
	JZ_INT32 nOffsetDestBuf = 0;


	
	if (nLength == 0)
	{
		*pwszDest = '\0';
		return(JZ_SUCCESS);
	}

	while (nOffsetSrcBuf < nLength)
	{
		if (!((*(pszSrc + nOffsetSrcBuf )) & 0x80))
		{
			*(pwszDest + nOffsetDestBuf) = *(pszSrc + nOffsetSrcBuf ) ;
			nOffsetSrcBuf += 1;
		}
		else
		{
			nUniCode = GetGb2UniIndex((unsigned char *)(pszSrc + nOffsetSrcBuf));
			*(pwszDest + nOffsetDestBuf)  = nUniCode;
			nOffsetSrcBuf += 2;
		}

		nOffsetDestBuf += 1;
	}
	*(pwszDest + nOffsetDestBuf)  = 0x00;
	
	return(JZ_SUCCESS);
	
}

